package com.tiger.sendmessage.wechatapi;


import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiger.sendmessage.type.WechatConfig;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Objects;

@Service
public class Wechatapi {
    private String access_token;
    private final WechatConfig wechatConfig;

    public Wechatapi(WechatConfig wechatConfig) {
        this.wechatConfig = wechatConfig;
    }

    @Async
    public void getAccessToken() {
        String url = String.format(wechatConfig.getAccessTokenUrl(), wechatConfig.getGzhAppid(), wechatConfig.getGzhSecret());

        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity entity = new HttpEntity<>(headers);


        String data = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();


        ObjectMapper objectMapper = new ObjectMapper();

        System.out.println("-------------获取到微信toke--------------------");

        try {
            HashMap responseMap = objectMapper.readValue(data, HashMap.class);

            System.out.println(responseMap);

            if(!responseMap.containsKey("errcode")) {
                access_token = (String) responseMap.get("access_token");
            }

        } catch (JsonProcessingException e) {
            System.out.println("-------------获取到微信token失败 --------------------");
            e.printStackTrace();
        }
    }

    @Async
    public void sendMsg(String touser, HashMap<String, HashMap<String, Object>> data, String url) {
        String apiUrl = String.format(wechatConfig.getSendMsgUrl(), access_token);

        HashMap<String, Object> msg = new HashMap<>();
        msg.put("touser", touser);
        msg.put("template_id", wechatConfig.getMsgTemplateId());

        if(url != null && !url.isEmpty()) {
            msg.put("url", url);
        }

        msg.put("data", data);



        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(msg), headers);

        template.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        ResponseEntity<String> r = template.postForEntity(apiUrl, requestEntity, String.class);
        if(Objects.equals(touser, "oYn7A6Q-QSW0GhByLLTkOkdMjRmQ")) {
            System.out.println(r);
        }

    }
}
